package org.rc.web;

import com.google.appengine.api.users.User;
import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;
import java.io.IOException;
import java.util.HashSet;
import java.util.Set;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.rc.dao.GenericDao;
import org.rc.model.AppUser;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 *
 * @author dokeeffe
 */
public class LoginRequiredServlet extends IndexServlet {
    
    private static final Logger LOGGER = LoggerFactory.getLogger(LoginRequiredServlet.class);
    private UserService userService = UserServiceFactory.getUserService();
    private GenericDao<AppUser> appUserDao = new GenericDao<AppUser>(AppUser.class);
    
    /**
     * Process GET. 
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException 
     */
    @Override
    protected void doGet(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException {

        String action = request.getParameter("action");
        
        User user = userService.getCurrentUser();
        String destinationUrl = request.getParameter("returnto");
        LOGGER.debug("return to "+destinationUrl);
        if(destinationUrl==null) {
            destinationUrl=request.getRequestURI();
        }
        if(user!=null && userService.isUserLoggedIn()) {
            if("logout".equals(action)) {
                response.sendRedirect(userService.createLogoutURL("/index"));
            } else {
                //create new user in datastore if needed
                AppUser appUser = appUserDao.getByProperty("user", user);
                if(appUser==null) {
                    appUser = new AppUser();
                    appUser.setUser(user);
                    appUser.setIdentifier(user.getEmail());
                    appUserDao.put(appUser);
                    response.sendRedirect("/welcome");
                } else {
                    //logged in already. redirect to index
                    response.sendRedirect("/index");
                }
            }
        } else {
            //not logged in and verify: redirect to openid provider
            if ("verify".equals(action)) {
                String providerUrl = request.getParameter("openid_identifier");
                Set<String> attributes = new HashSet();
                String loginUrl = userService.createLoginURL(destinationUrl, null, providerUrl, attributes);
                LOGGER.debug("redirecting to " + loginUrl);
                response.sendRedirect(loginUrl);
            } else {
                request.setAttribute("returnto", destinationUrl);
                forward(request, response, "/loginrequired.jsp");
            }
        }
    }
}
